<template>
  <div>
    <div style="margin-bottom: 50px">
      <button @click="startRecording">btn开始录音</button>
      <button @click="stopRecording" :disabled="!isRecording">btn停止录音</button>
    </div>

    <button
      style="margin-bottom: 50px"
      @pointerdown="startRecording"
      @pointerup="stopRecording"
      @pointercancel="stopRecording"
    >
      btn触摸开始和抬起结束
    </button>

    <div
      style="margin-bottom: 50px"
      @pointerdown="startRecording"
      @pointerup="stopRecording"
      @pointercancel="stopRecording"
    >
      触摸开始和抬起结束
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      mediaStream: null,
      audioTrack: null,
      isRecording: false
    }
  },
  methods: {
    async startRecording() {
      console.log("开始录音")
      try {
        this.mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true })
        this.audioTrack = this.mediaStream.getAudioTracks()[0]
        this.isRecording = true
      } catch (error) {
        console.error("Error accessing microphone:", error)
      }
    },
    stopRecording() {
      console.log("结束录音")
      if (this.audioTrack) {
        this.audioTrack.stop()
        if (this.audioTrack.readyState === "ended" || track.state === "ended") {
          console.log("关闭轨道1状态成功")
        } else {
          console.log("关闭轨道1状态失败")
        }
        this.isRecording = false
        // 清除媒体流引用
        this.mediaStream = null
        this.audioTrack = null
      }
    }
  },
  // 当组件被缓存时触发
  deactivated() {
    console.log("当组件被缓存时触发,手动清除")
    this.stopRecording()
  },
  // 当组件被激活时触发
  activated() {
    // 可以在这里重新初始化状态
    this.isRecording = false
  }
}
</script>